package tests.update;

import static org.junit.Assert.fail;

import java.util.ArrayList;

import model.Budget;
import model.BudgetFactory;
import model.Line;
import model.Subline;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.workplicity.util.Helper;
import org.workplicity.worklet.WorkletContext;

import cc.test.bridge.LineInterface;

import com.mongodb.BasicDBObject;
import com.mongodb.util.JSON;

/*
 * 
 * Attempts to change the name of a line of a
 * budget that already contains the line
 * 
 */

public class LineUpdateNameTest00
{
	Budget budget;
	Line line;
	Subline subline;
	BudgetFactory factory;

	@BeforeClass
	public static void setUpBeforeClass() throws Exception
	{
	}

	@AfterClass
	public static void tearDownAfterClass() throws Exception
	{
	}

	@Before
	public void setUp() throws Exception
	{
		System.out.println("Begining test: " +this.getClass());
		System.out.println("Setup");
		
		factory = new BudgetFactory();
		
		//Create a budget
        budget = (Budget) factory.create();
        budget.setName("Test budget");
        
        budget.setDescription("This is an update test budget.");
        
        line = (Line) budget.createLine();
        budget.add(line);
        
        budget.commit();
	}

	@After
	public void tearDown() throws Exception
	{
		System.out.println("Tear down");

		Helper.delete(subline, "Sublines", WorkletContext.getInstance());
		Helper.delete(line, "Lines", WorkletContext.getInstance());
		Helper.delete(budget, "Budgets", WorkletContext.getInstance());
	}

	@Test
	public void test()
	{        
	 	 try
		 {
	 		 line.setName("Charity");
	 		 budget.commit();
	 		 
	 		 BasicDBObject criteria = new BasicDBObject("entry.id", line.getId());
	 		 String predicate = JSON.serialize(criteria);
	         
			 @SuppressWarnings("unchecked")
			 ArrayList<LineInterface> lines = Helper.query("Lines", predicate, WorkletContext.getInstance());
            
	         if(!((Line) lines.get(0)).getName().equals("Charity"))
	         {
	        	 fail("Update line name to 'Charity' failed");
	         }            
        }
        catch(Exception e)
        {
            fail("Updating line failed with exception: " + e);
        }
	}
}
